namespace DotNetNuke.UI.Utilities
{
    using DotNetNuke.Common;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Services.Localization;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    /// -----------------------------------------------------------------------------
    /// Project	 : DotNetNuke
    /// Class	 : ClientAPI
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// Library responsible for interacting with DNN Client API.
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [Jon Henning]	8/3/2004	Created
    /// </history>
    /// -----------------------------------------------------------------------------
    public class DNNClientAPI
    {
        private static void AddAttribute(Control objControl, string strName, string strValue)
        {
            if (objControl is HtmlControl)
            {
                ((HtmlControl) objControl).Attributes.Add(strName, strValue);
            }
            else if (objControl is WebControl)
            {
                ((WebControl) objControl).Attributes.Add(strName, strValue);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Adds client side body.onload event handler 
        /// </summary>
        /// <param name="objPage">Current page rendering content</param>
        /// <param name="strJSFunction">Javascript function name to execute</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Jon Henning]	8/3/2004	Created
        /// [Jon Henning]	4/25/2005	registering dnn namespace when this function is utilized
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void AddBodyOnloadEventHandler(Page objPage, string strJSFunction)
        {
            if (!strJSFunction.EndsWith(";"))
            {
                strJSFunction = strJSFunction + ";";
            }
            ClientAPI.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn);
            if (ClientAPI.GetClientVariable(objPage, "__dnn_pageload").IndexOf(strJSFunction) == -1)
            {
                ClientAPI.RegisterClientVariable(objPage, "__dnn_pageload", strJSFunction, false);
            }
        }

        private static void AddStyleAttribute(Control objControl, string strName, string strValue)
        {
            if (objControl is HtmlControl)
            {
                if (Strings.Len(strValue) > 0)
                {
                    ((HtmlControl) objControl).Style.Add(strName, strValue);
                }
                else
                {
                    ((HtmlControl) objControl).Style.Remove(strName);
                }
            }
            else if (objControl is WebControl)
            {
                if (Strings.Len(strValue) > 0)
                {
                    ((WebControl) objControl).Style.Add(strName, strValue);
                }
                else
                {
                    ((WebControl) objControl).Style.Remove(strName);
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Allows any module to have drag and drop functionality enabled
        /// </summary>
        /// <param name="objTitle">Title element that responds to the click and dragged</param>
        /// <param name="objContainer"></param>
        /// <remarks>
        /// This sub also will send down information to notify the client of the panes that have been defined in the current skin.
        /// </remarks>
        /// <history>
        /// [Jon Henning]	8/9/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void EnableContainerDragAndDrop(Control objTitle, Control objContainer, int ModuleID)
        {
            if (((!ClientAPI.ClientAPIDisabled() && ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.Positioning)) ? 1 : 0) != 0)
            {
                IEnumerator refObjectHelperL0=null;
                AddBodyOnloadEventHandler(objTitle.Page, "__dnn_enableDragDrop()");
                ClientAPI.RegisterClientReference(objTitle.Page, ClientAPI.ClientNamespaceReferences.dnn_dom_positioning);
                ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_dragDrop", objContainer.ClientID + " " + objTitle.ClientID + " " + ModuleID.ToString() + ";", false);
                string strPanes = "";
                string strPaneNames = "";
                PortalSettings objPortalSettings = (PortalSettings) HttpContext.Current.Items["PortalSettings"];
                try
                {
                    refObjectHelperL0 = objPortalSettings.ActiveTab.Panes.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        string strPane = Conversions.ToString(refObjectHelperL0.Current);
                        Control objCtl = DotNetNuke.Common.Globals.FindControlRecursive(objContainer.Parent, strPane);
                        if (objCtl != null)
                        {
                            strPanes = strPanes + objCtl.ClientID + ";";
                        }
                        strPaneNames = strPaneNames + strPane + ";";
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_Panes", strPanes, true);
                ClientAPI.RegisterClientVariable(objTitle.Page, "__dnn_PaneNames", strPaneNames, true);
            }
        }

        public static void EnableMinMax(Control objButton, Control objContent, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType)
        {
            EnableMinMax(objButton, objContent, -1, blnDefaultMin, "", "", ePersistanceType);
        }

        public static void EnableMinMax(Control objButton, Control objContent, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType)
        {
            EnableMinMax(objButton, objContent, intModuleId, blnDefaultMin, "", "", ePersistanceType);
        }

        public static void EnableMinMax(Control objButton, Control objContent, bool blnDefaultMin, string strMinIconLoc, string strMaxIconLoc, MinMaxPersistanceType ePersistanceType)
        {
            EnableMinMax(objButton, objContent, -1, blnDefaultMin, strMinIconLoc, strMaxIconLoc, ePersistanceType);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Allows a button and a content area to support client side min/max functionality
        /// </summary>
        /// <param name="objButton">Control that when clicked causes content area to be hidden/shown</param>
        /// <param name="objContent">Content area that is hidden/shown</param>
        /// <param name="intModuleId">Module id of button/content, used only for persistance type of Cookie</param>
        /// <param name="blnDefaultMin">If content area is to be defaulted to minimized pass in true</param>
        /// <param name="strMinIconLoc">Location of minimized icon</param>
        /// <param name="strMaxIconLoc">Location of maximized icon</param>
        /// <param name="ePersistanceType">How to store current state of min/max.  Cookie, Page, None</param>
        /// <remarks>
        /// This method's purpose is to provide a higher level of abstraction between the ClientAPI and the module developer.
        /// </remarks>
        /// <history>
        /// [Jon Henning]	5/6/2005	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void EnableMinMax(Control objButton, Control objContent, int intModuleId, bool blnDefaultMin, string strMinIconLoc, string strMaxIconLoc, MinMaxPersistanceType ePersistanceType)
        {
            EnableMinMax(objButton, objContent, intModuleId, blnDefaultMin, strMinIconLoc, strMaxIconLoc, ePersistanceType, 5);
        }

        public static void EnableMinMax(Control objButton, Control objContent, int intModuleId, bool blnDefaultMin, string strMinIconLoc, string strMaxIconLoc, MinMaxPersistanceType ePersistanceType, int intAnimationFrames)
        {
            if (ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.DHTML))
            {
                ClientAPI.RegisterClientReference(objButton.Page, ClientAPI.ClientNamespaceReferences.dnn_dom);
                switch (((int) ePersistanceType))
                {
                    case 0:
                        AddAttribute(objButton, "onclick", "if (__dnn_SectionMaxMin(this,  '" + objContent.ClientID + "')) return false;");
                        if (Strings.Len(strMinIconLoc) > 0)
                        {
                            AddAttribute(objButton, "max_icon", strMaxIconLoc);
                            AddAttribute(objButton, "min_icon", strMinIconLoc);
                        }
                        break;

                    case 1:
                        AddAttribute(objButton, "onclick", "if (__dnn_SectionMaxMin(this,  '" + objContent.ClientID + "')) return false;");
                        if (Strings.Len(strMinIconLoc) > 0)
                        {
                            AddAttribute(objButton, "max_icon", strMaxIconLoc);
                            AddAttribute(objButton, "min_icon", strMinIconLoc);
                        }
                        break;

                    case 2:
                        if (intModuleId == -1)
                        {
                            throw new Exception("MinMax persistance type of cookie requires a ModuleId");
                        }
                        AddAttribute(objButton, "onclick", "if (__dnn_ContainerMaxMin_OnClick(this, '" + objContent.ClientID + "')) return false;");
                        AddAttribute(objButton, "containerid", intModuleId.ToString());
                        AddAttribute(objButton, "cookieid", "_Module" + intModuleId.ToString() + "_Visible");
                        ClientAPI.RegisterClientVariable(objButton.Page, "min_icon_" + intModuleId.ToString(), strMinIconLoc, true);
                        ClientAPI.RegisterClientVariable(objButton.Page, "max_icon_" + intModuleId.ToString(), strMaxIconLoc, true);
                        ClientAPI.RegisterClientVariable(objButton.Page, "max_text", DotNetNuke.Services.Localization.Localization.GetString("Maximize"), true);
                        ClientAPI.RegisterClientVariable(objButton.Page, "min_text", DotNetNuke.Services.Localization.Localization.GetString("Minimize"), true);
                        if (blnDefaultMin)
                        {
                            ClientAPI.RegisterClientVariable(objButton.Page, "__dnn_" + intModuleId.ToString() + ":defminimized", "true", true);
                        }
                        break;
                }
                if (get_MinMaxContentVisibile(objButton, intModuleId, blnDefaultMin, ePersistanceType))
                {
                    AddStyleAttribute(objContent, "display", "");
                    if (Strings.Len(strMinIconLoc) > 0)
                    {
                        SetMinMaxProperties(objButton, strMinIconLoc, DotNetNuke.Services.Localization.Localization.GetString("Minimize"), DotNetNuke.Services.Localization.Localization.GetString("Minimize"));
                    }
                }
                else
                {
                    AddStyleAttribute(objContent, "display", "none");
                    if (Strings.Len(strMaxIconLoc) > 0)
                    {
                        SetMinMaxProperties(objButton, strMaxIconLoc, DotNetNuke.Services.Localization.Localization.GetString("Maximize"), DotNetNuke.Services.Localization.Localization.GetString("Maximize"));
                    }
                }
                if (intAnimationFrames != 5)
                {
                    AddAttribute(objButton, "animf", intAnimationFrames.ToString());
                }
            }
        }

        private static void SetImageProperties(Control objControl, string strImage, string strToolTip, string strAltText)
        {
            bool refBoolHelperL0 = true;
            if (refBoolHelperL0 == (objControl is Image))
            {
                Image objImage = (Image) objControl;
                objImage.ImageUrl = strImage;
                objImage.AlternateText = strAltText;
                objImage.ToolTip = strToolTip;
            }
            else if (refBoolHelperL0 == (objControl is ImageButton))
            {
                ImageButton objImage = (ImageButton) objControl;
                objImage.ImageUrl = strImage;
                objImage.AlternateText = strAltText;
                objImage.ToolTip = strToolTip;
            }
            else if (refBoolHelperL0 == (objControl is HtmlImage))
            {
                HtmlImage objImage = (HtmlImage) objControl;
                objImage.Src = strImage;
                objImage.Alt = strAltText;
            }
        }

        private static void SetMinMaxProperties(Control objButton, string strImage, string strToolTip, string strAltText)
        {
            bool refBoolHelperL0 = true;
            if (refBoolHelperL0 == (objButton is LinkButton))
            {
                LinkButton objLB = (LinkButton) objButton;
                objLB.ToolTip = strToolTip;
                if (objLB.Controls.Count > 0)
                {
                    SetImageProperties(objLB.Controls[0], strImage, strToolTip, strAltText);
                }
            }
            else if (refBoolHelperL0 == (objButton is Image))
            {
                SetImageProperties((Image) objButton, strImage, strToolTip, strAltText);
            }
            else if (refBoolHelperL0 == (objButton is ImageButton))
            {
                SetImageProperties((LinkButton) objButton, strImage, strToolTip, strAltText);
            }
        }

        //public /*static*/ bool this[Control objButton, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType]
        //{
        //    get
        //    {
        //        bool MinMaxContentVisibile;
        //        if (HttpContext.Current != null)
        //        {
        //            switch (((int) ePersistanceType))
        //            {
        //                case 1:
        //                {
        //                    string sExpanded = ClientAPI.GetClientVariable(objButton.Page, objButton.ClientID + ":exp");
        //                    if (Strings.Len(sExpanded) <= 0)
        //                    {
        //                        return !blnDefaultMin;
        //                    }
        //                    return Conversions.ToBoolean(sExpanded);
        //                }
        //                case 2:
        //                {
        //                    if (intModuleId == -1)
        //                    {
        //                        throw new Exception("MinMax persistance type of cookie requires a ModuleId");
        //                    }
        //                    HttpCookie objModuleVisible = HttpContext.Current.Request.Cookies["_Module" + intModuleId.ToString() + "_Visible"];
        //                    if (objModuleVisible != null)
        //                    {
        //                        return (objModuleVisible.Value != "false");
        //                    }
        //                    return !blnDefaultMin;
        //                }
        //            }
        //        }
        //        return MinMaxContentVisibile;
        //    }
        //    set
        //    {
        //        if (HttpContext.Current != null)
        //        {
        //            switch (((int) ePersistanceType))
        //            {
        //                case 1:
        //                    ClientAPI.RegisterClientVariable(objButton.Page, objButton.ClientID + ":exp", ((int) -(value > false)).ToString(), true);
        //                    break;

        //                case 2:
        //                {
        //                    HttpCookie objModuleVisible = new HttpCookie("_Module" + intModuleId.ToString() + "_Visible");
        //                    if (objModuleVisible != null)
        //                    {
        //                        objModuleVisible.Value = value.ToString().ToLower();
        //                        objModuleVisible.Expires = DateTime.MaxValue;
        //                        HttpContext.Current.Response.AppendCookie(objModuleVisible);
        //                    }
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}

        //public /*static*/ bool this[Control objButton, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType]
        //{
        //    get
        //    {
        //        return get_MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType);
        //    }
        //    set
        //    {
        //        set_MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value);
        //    }
        //}

        public enum MinMaxPersistanceType
        {
            None,
            Page,
            Cookie
        }

        public static bool get_MinMaxContentVisibile(Control objButton,int moduleId, bool blnDefaultMin,
    MinMaxPersistanceType ePersistanceType)
        {
            if (System.Web.HttpContext.Current != null)
            {
                switch (ePersistanceType)
                {
                    case MinMaxPersistanceType.Page:
                        string sExpanded = DotNetNuke.UI.Utilities.ClientAPI.GetClientVariable(objButton.Page, objButton.ClientID + ":exp");
                        if (Strings.Len(sExpanded) > 0) return Convert.ToBoolean(sExpanded);
                        else return !blnDefaultMin;
                        break;
                    case MinMaxPersistanceType.Cookie:
                        if (moduleId == -1) throw new Exception("MinMax persistance type of cookies require a ModuleId");
                        HttpCookie objModulevisible = HttpContext.Current.Request.Cookies["_Module" + moduleId.ToString() + "_Visible"];
                        if (objModulevisible != null) return !objModulevisible.Value.Equals("false");
                        else return !blnDefaultMin;
                        break;
                }
            }
            throw new System.ArgumentOutOfRangeException("Wrong PersistanceType");
        }
        public static void set_MinMaxContentVisibile(Control objButton,int moduleId,bool blnDefaultMin,
    MinMaxPersistanceType ePersistanceType, bool newValue)
        {
            if (HttpContext.Current != null)
            {
                switch (ePersistanceType)
                {
                    case MinMaxPersistanceType.Page:
                        DotNetNuke.UI.Utilities.ClientAPI.RegisterClientVariable(objButton.Page,objButton.ClientID+":exp",Convert.ToInt32(newValue).ToString(),true);
                        break;
                    case MinMaxPersistanceType.Cookie:
                        HttpCookie objModuleVisible = new HttpCookie("_Module" + moduleId.ToString() + "_Visible");
                        if (objModuleVisible != null)
                        {
                            objModuleVisible.Value = newValue.ToString().ToLower();
                            objModuleVisible.Expires = DateTime.MaxValue;
                            HttpContext.Current.Response.AppendCookie(objModuleVisible);
                        }
                        break;
                }
            }
        }

        public static bool get_MinMaxContentVisibile(Control objButton, bool blnDefaultMin,
            MinMaxPersistanceType ePersistanceType)
        {
            return get_MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType);
        }
        public static void set_MinMaxContentVisibile(Control objButton, bool blnDefaultMin,
    MinMaxPersistanceType ePersistanceType,bool newValue)
        {
            set_MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType,newValue);
        }




    }
}

